package com.example.suntest.group;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Package: com.at.mrp.bll.service.group
 * @ClassName: GroupingService
 * @Author: sgq
 * @Date: 2024/8/12 9:06
 * @Description: TODD
 */
@Component
public class GroupingService {
    public <T, R> Map<R, List<T>> group(List<T> list, List<GroupingStrategy<T, R>> strategies) {
        if (strategies.isEmpty()) {
            throw new IllegalArgumentException("至少要有一个分组策略.");
        }

        Map<R, List<T>> map = new HashMap<>();
        // 使用第一个分组策略开始分组
        Function<T, R> keyExtractor = strategies.get(0);
        Map<R, List<T>> grouped = list.stream()
                .collect(Collectors.groupingBy(keyExtractor));

        // 使用第二个分组策略开始分组
        Function<T, R> keyExtractor2 = strategies.get(1);
        for (int i = 0; i < grouped.keySet().size(); i++) {
            List<T> value = grouped.get(grouped.keySet().toArray()[i]);
//            Map<R, List<T>> grouped2 = value.stream()
////                    .collect(Collectors.groupingBy(keyExtractor2));
//            Map<R, List<T>> grouped2 = value.stream()
//                    .collect(Collectors.toMap(grouped.keySet().toArray()[i],value.stream().collect(Collectors.groupingBy(keyExtractor2),(a,b)->a)));
//            System.out.println();
        }


//        // 如果还有更多的分组策略，则继续嵌套分组
//        for (int i = 1; i < strategies.size(); i++) {
//            keyExtractor = strategies.get(i);
//            grouped = grouped.values().stream()
//                    .flatMap(List::stream)
//                    .collect(Collectors.groupingBy(keyExtractor));
//        }

        return map;
    }

}
